const bcrypt = require('bcryptjs')
const { getUserInfo } = require('../service/user.service')
const {
  userFormatError,
  userExists,
  userRegisterError,
  userNotExists,
  userLoginError,
  invalidPassword,
  invalidEmail
} = require('../constant/err.type')

const userValidator = async (ctx, next) => {
  const { email, password } = ctx.request.body
  if (!email || !password) {
    console.error('用户名或密码为空', ctx.request.body)
    return ctx.app.emit('error', userFormatError, ctx)
  }
  await next()
}

const isEmail = async (ctx, next) => {
  const { email } = ctx.request.body
  const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
  if (!reg.test(email)) {
    console.error('邮箱格式不正确', email)
    return ctx.app.emit('error', invalidEmail, ctx)
  }
  await next()
}

const verifyUser = async (ctx, next) => {
  const { email } = ctx.request.body

  try {
    const res = await getUserInfo({ email })
    if (res) {
      console.error('用户名已经存在', email)
      return ctx.app.emit('error', userExists, ctx)
    }
  } catch (err) {
    console.err('获取用户信息错误', err)
    return ctx.app.emit('error', userRegisterError, ctx)
  }
  await next()
}

const bcryptPassword = async (ctx, next) => {
  const { password } = ctx.request.body
  const salt = bcrypt.genSaltSync(10)
  ctx.request.body.password = bcrypt.hashSync(password, salt)

  await next()
}

const verifyLogin = async (ctx, next) => {
  const { email, password } = ctx.request.body
  const res = await getUserInfo({ email })

  try {
    if (!res) {
      console.error('用户不存在', email)
      return ctx.app.emit('error', userNotExists, ctx)
    }

    if (!bcrypt.compareSync(password, res.password)) {
      console.error('密码不匹配')
      return ctx.app.emit('error', invalidPassword, ctx)
    }
  } catch (err) {
    console.error('用户登录失败', err)
    return ctx.app.emit('error', userLoginError, ctx)
  }
  await next()
}

module.exports = {
  userValidator,
  verifyUser,
  isEmail,
  bcryptPassword,
  verifyLogin
}
